package com.lyon.demo.netty.core.bytebuf;

import com.lyon.demo.rpc.api.core.Command;
import com.lyon.demo.rpc.api.core.Header;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;

import java.util.Objects;

/**
 * @author LeeYan9
 * @since 2022-04-18
 */
@SuppressWarnings("unused")
public class CommandEncoder extends MessageToByteEncoder<Command> {

    @Override
    protected void encode(ChannelHandlerContext ctx, Command command, ByteBuf byteBuf) throws Exception {
        if (Objects.isNull(command)) {
            return;
        }
        // 写入字节长度
        byteBuf.writeInt(Integer.BYTES + command.length());
        encodeHeader(ctx, command.getHeader(), byteBuf);
        encodeCommand(ctx, command, byteBuf);
    }

    protected void encodeCommand(ChannelHandlerContext ctx, Command command, ByteBuf byteBuf) {
        if (Objects.nonNull(command.getPayload())) {
            byteBuf.writeBytes(command.getPayload());
        }
    }

    protected void encodeHeader(ChannelHandlerContext ctx, Header header, ByteBuf byteBuf) {
        byteBuf.writeInt(header.getType());
        byteBuf.writeInt(header.getVersion());
        byteBuf.writeLong(header.getRequestId());
    }

}
